package com.syxp.pda.core.command;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

import com.syxp.pda.core.bean.FieldBean;
import com.syxp.pda.core.util.Operation;

public class ProjectionCommand implements CriteriaCommand{

	private List<FieldBean> fields ;
	
	public ProjectionCommand(List<FieldBean> fields) {
		this.fields = fields ;
	}
	
	@Override
	public Criteria execute(Criteria criteria) {
		ProjectionList projectionList = Projections.projectionList() ;
		for(FieldBean field : fields) {
			if(field.getOperation()==null){
				projectionList.add(Projections.property(field.getProperty())) ;
			} else if (StringUtils.equals(field.getOperation(), Operation.MAX)) {
				projectionList.add(Projections.max(field.getProperty())) ;
			} else if(StringUtils.equals(field.getOperation(), Operation.MIN)) {
				projectionList.add(Projections.min(field.getProperty())) ;
			} else if(StringUtils.equals(field.getOperation(), Operation.COUNT)) {
				projectionList.add(Projections.count(field.getProperty())) ;
			} else if(StringUtils.equals(field.getOperation(), Operation.GROUP)) {
				projectionList.add(Projections.groupProperty(field.getProperty())) ;
			} else if(StringUtils.equals(field.getOperation(), Operation.DISTINCT)) {
				projectionList.add(Projections.distinct(Projections.property(field.getProperty())));
			}
		}
		criteria.setProjection(projectionList) ;
		return criteria;
	}

}
